package com.supor.aiot.mine.ui.cooking;

import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.base.DataApiResult;
import com.android.baseconfig.common.config.HttpConstant;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.google.gson.reflect.TypeToken;
import com.supor.aiot.common.app.api.FileUploadImpl;
import com.supor.aiot.common.base.BaseViewModel;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.entity.UploadResultBean;
import com.supor.aiot.mine.api.CookingRecordImpl;
import com.supor.aiot.mine.bean.CookingEvalDetail;
import com.supor.aiot.mine.bean.CookingRecordBean;
import com.supor.aiot.mine.bean.CookingRecordNumBean;
import com.supor.aiot.mine.bean.RecipeEvalBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import autodispose2.AutoDisposeConverter;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.RequestBody;

/**
 * @author: zook
 * @date: 2021/10/15
 */
public class CookingRecordModel extends BaseViewModel {
    public final static int COOK_RECORD_PAGE_SIZE = 30;
    private MutableLiveData<BaseApiResult<DataApiResult<List<CookingRecordBean>>>> cookingRecordListResult = new MutableLiveData<>();
    private MutableLiveData<Result> uploadResult = new MutableLiveData<>();
    private MutableLiveData<List<UploadResultBean>> videoUrlArray = new MutableLiveData<>();
    private MutableLiveData<List<UploadResultBean>> imgUrlArray = new MutableLiveData<>();
    private MutableLiveData<Result<CookingRecordNumBean>> cookingNumResult = new MutableLiveData<>();
    private MutableLiveData<Result<CookingEvalDetail>> cookingEvalDetailResult = new MutableLiveData<>();
    private MutableLiveData<Result<RecipeEvalBean>> evalSubmitResult = new MutableLiveData<>();

    public CookingRecordModel(@NonNull Application application) {
        super(application);
    }

    public void getCookingRecordList(String macArr, int isEval, int page,
                                     AutoDisposeConverter<BaseApiResult<DataApiResult<List<CookingRecordBean>>>> autoDisposeConverter) {
        Observable<BaseApiResult<DataApiResult<List<CookingRecordBean>>>> observable = null;
        if (isEval == -1) {
            if (TextUtils.isEmpty(macArr)) {
                observable = CookingRecordImpl.getInstance()
                        .getCookingRecordList(page, COOK_RECORD_PAGE_SIZE);
            } else {
                observable = CookingRecordImpl.getInstance()
                        .getCookingRecordListWithMacArr(macArr, page, COOK_RECORD_PAGE_SIZE);
            }
        } else {
            if (TextUtils.isEmpty(macArr)) {
                observable = CookingRecordImpl.getInstance()
                        .getCookingRecordList(isEval, page, COOK_RECORD_PAGE_SIZE);
            } else {
                observable = CookingRecordImpl.getInstance()
                        .getCookingRecordListWithMacArr(isEval, macArr, page, COOK_RECORD_PAGE_SIZE);
            }
        }
        observable.
                to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<DataApiResult<List<CookingRecordBean>>>>() {
                    @Override
                    public void accept(BaseApiResult<DataApiResult<List<CookingRecordBean>>> dataApiResultBaseApiResult) throws Exception {
                        cookingRecordListResult.setValue(dataApiResultBaseApiResult);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {

                    }
                });
    }

    public void getCookingNum(AutoDisposeConverter<BaseApiResult<CookingRecordNumBean>> autoDisposeConverter) {
        CookingRecordImpl.getInstance().getCookingNum()
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<CookingRecordNumBean>>() {
                    @Override
                    public void accept(BaseApiResult<CookingRecordNumBean> cookingRecordNumBeanBaseApiResult) throws Exception {
                        cookingNumResult.setValue(new Result.Success<>(cookingRecordNumBeanBaseApiResult.data));
                    }
                });
    }

    public void submitRecipeEval(
            String logId,//烹饪记录id
            int satisfaction,//满意度 1一般；2还不错；3太赞了
            String satisfiedLabels,//满意度标签
            String supplementary,//说点什么
            String evaluateImage,//图片
            String evaluateVideo,//视频
            int syn,//是否同步到社区 1同步0不同步
            AutoDisposeConverter<BaseApiResult<RecipeEvalBean>> autoDisposeConverter
    ) {

        JSONObject jsonObject = new JSONObject();
        RequestBody requestBody = null;
        try {
            jsonObject.put("logId", logId);
            jsonObject.put("evaluateType", "COOKREPLY");
            jsonObject.put("satisfaction", satisfaction);
            jsonObject.put("satisfiedLabels", satisfiedLabels);
            jsonObject.put("supplementary", supplementary);
            jsonObject.put("evaluateImage", evaluateImage);
            jsonObject.put("evaluateVideo", evaluateVideo);
            jsonObject.put("note", syn);
            requestBody = RequestBody.create(HttpConstant.JSON,
                    jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        CookingRecordImpl.getInstance().submitEval(requestBody)
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<RecipeEvalBean>>() {
                    @Override
                    public void accept(BaseApiResult<RecipeEvalBean> recipeEvalBeanBaseApiResult) throws Exception {
                        evalSubmitResult.setValue(new Result.Success<>(recipeEvalBeanBaseApiResult.data));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Logc.e("accept: " + throwable);
                    }
                });
    }

    public void uploadFile(List<String> photoPaths, List<String> videoPaths) {
        if (photoPaths.size() != 0) {
            uploadPhoto(photoPaths);
        } else if (videoPaths.size() != 0) {
            uploadVideo(videoPaths);
        }
    }

    /**
     * 上传图片
     *
     * @param pathList 图片路径列表
     */
    public void uploadPhoto(final List<String> pathList) {
        List<File> files = new ArrayList<>();
        for (String s : pathList) {
            File file = new File(s);
            files.add(file);
        }
        FileUploadImpl.getInstance().uploadFiles("photo", files).subscribe(result -> {
            Logc.i("uploadFiles: " + result);
            JSONObject jsonObject = new JSONObject(result);
            if ("success".equalsIgnoreCase(jsonObject.getString("result"))) {
                List<UploadResultBean> uploadResultBeans =
                        GsonUtil.getInstance().toObject(jsonObject.getString("fileUrls"),
                                new TypeToken<List<UploadResultBean>>() {
                                }.getType());
                imgUrlArray.setValue(uploadResultBeans);
            } else {
                uploadResult.setValue(new Result.Error("upload photo failed"));
            }
        }, throwable -> {
            Logc.e("uploadFiles: " + throwable);
            uploadResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    /**
     * 上传视频
     *
     * @param pathList 视频路径列表
     */
    public void uploadVideo(final List<String> pathList) {
        List<File> files = new ArrayList<>();
        for (String s : pathList) {
            File file = new File(s);
            files.add(file);
        }
        FileUploadImpl.getInstance().uploadFiles("video", files).subscribe(result -> {
            Logc.i("uploadFiles: " + result);
            JSONObject jsonObject = new JSONObject(result);
            if ("success".equalsIgnoreCase(jsonObject.getString("result"))) {
                List<UploadResultBean> uploadResultBeans =
                        GsonUtil.getInstance().toObject(jsonObject.getString("fileUrls"),
                                new TypeToken<List<UploadResultBean>>() {
                                }.getType());
                videoUrlArray.setValue(uploadResultBeans);
            } else {
                uploadResult.setValue(new Result.Error("upload video failed"));
            }
        }, throwable -> {
            Logc.e("uploadFiles: " + throwable);
            uploadResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    public void getCookingEvalDetail(String id, AutoDisposeConverter<BaseApiResult<CookingEvalDetail>> autoDisposeConverter) {
        CookingRecordImpl.getInstance().getCookingEvalDetail(id)
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<CookingEvalDetail>>() {
                    @Override
                    public void accept(BaseApiResult<CookingEvalDetail> cookingEvalDetailBaseApiResult) throws Exception {
                        cookingEvalDetailResult.setValue(new Result.Success<>(cookingEvalDetailBaseApiResult.data));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Logc.e(throwable.getMessage());
                    }
                });
    }

    public MutableLiveData<Result<CookingRecordNumBean>> getCookingNumResult() {
        return cookingNumResult;
    }

    public MutableLiveData<BaseApiResult<DataApiResult<List<CookingRecordBean>>>> getCookingRecordListResult() {
        return cookingRecordListResult;
    }

    public MutableLiveData<List<UploadResultBean>> getVideoUrlArray() {
        return videoUrlArray;
    }

    public MutableLiveData<List<UploadResultBean>> getImgUrlArray() {
        return imgUrlArray;
    }

    public MutableLiveData<Result<CookingEvalDetail>> getCookingEvalDetailResult() {
        return cookingEvalDetailResult;
    }

    public MutableLiveData<Result<RecipeEvalBean>> getEvalSubmitResult() {
        return evalSubmitResult;
    }

    public MutableLiveData<Result> getUploadResult() {
        return uploadResult;
    }
}
